﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using JustinAngel.Neurons.Services;
using Microsoft.Devices;
using Ninject;

namespace JustinAngel.UnitedNationsNews.Services
{
    public interface IZuneMediaHubIntegrationService
    {
        void PlayingItem(ZuneHistoryItem zuneHistoryItem);
        ZuneHistoryItem LoadHistoryOrNowPlayingTileClick(NavigationContext NavigationContext);
    }

    public class ZuneMediaHubIntegrationService : IZuneMediaHubIntegrationService
    {
        [Inject]
        public IImageService ImageServiceInstance { get; set; }

        static object mutex = new object();


        public void PlayingItem(ZuneHistoryItem zuneHistoryItem)
        {
        

            ImageServiceInstance.GetImageData(zuneHistoryItem.ImageUri,
                                              zuneHistoryItem.Title,
            (img, state) =>
            {
                try
                {
                    var stateHistoryItem = (ZuneHistoryItem) state;
                    if (img != null)
                    {
                        Stream HistoryTileImageStream = BuildTile(img, 173, 173, stateHistoryItem.AppDisplayName);
                        Stream NowPlayingTileImageStream = BuildTile(img, 358, 358);
                        if (HistoryTileImageStream != null)
                        {
                            lock (mutex)
                            {
                                MediaHistoryItem item = new MediaHistoryItem();
                                item.Source = stateHistoryItem.Source;
                                item.PlayerContext.Add("historyTile", "true");
                                //item.PlayerContext.Add("historyTitle", stateHistoryItem.Title);
                                item.PlayerContext.Add("historySourceUrl", stateHistoryItem.Source);
                                item.PlayerContext.Add("historyTag", stateHistoryItem.Tag);
                                item.Title = stateHistoryItem.AppDisplayName;

                                item.ImageStream = HistoryTileImageStream;
                                MediaHistory.Instance.WriteRecentPlay(item);

                                item.ImageStream = NowPlayingTileImageStream;
                                item.PlayerContext.Remove("historyTile");
                                item.PlayerContext.Add("historyIsNowPlayingTile", "true");
                                MediaHistory.Instance.NowPlaying = item;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // just move on if writing history fails, it's not mission critical
                }
            }, zuneHistoryItem);
        }

        Stream BuildTile(ImageSource image, int width, int height, string Text = null)
        {
            Grid g = new Grid
                         {
                             Width = width,
                             Height = height,
                             VerticalAlignment = VerticalAlignment.Bottom
                         };

            Image img = new Image
                            {
                                Source = image,
                                Stretch = Stretch.UniformToFill,
                                Width = width,
                                Height = height,
                                HorizontalAlignment = HorizontalAlignment.Stretch,
                                VerticalAlignment = VerticalAlignment.Stretch
                            };

            g.Children.Add(img);

            if (!string.IsNullOrEmpty(Text))
            {
                TextBlock textBlock = new TextBlock()
                                          {
                                              Text = Text,
                                              Foreground = new SolidColorBrush(Colors.White),
                                              Margin = new Thickness(4, 150, 0, 0),
                                              TextWrapping = TextWrapping.Wrap,
                                              Width = width - 4,
                                              MaxHeight = 20,
                                              Clip = new RectangleGeometry() { Rect = new Rect(0, 0, width - 4, 20 ) },
                                              FontSize = 15,
                                              FontWeight = FontWeights.SemiBold
                                          };
                g.Children.Add(textBlock);

            }
            g.InvalidateMeasure();
            g.InvalidateArrange();
            g.UpdateLayout();
            WriteableBitmap b = new WriteableBitmap(g, null);

            // attempt to save until stream size is small enough to fit
            int jpegQuality = 80;
            Stream compositeStream;
            do
            {
                compositeStream = new MemoryStream();
                b.SaveJpeg(compositeStream, width, height, 0, jpegQuality);
                compositeStream.Seek(0, SeekOrigin.Begin);
                jpegQuality -= 10;
            } while (compositeStream.Length > 16383 && jpegQuality > 0);
            return compositeStream;
        }

        public ZuneHistoryItem LoadHistoryOrNowPlayingTileClick(NavigationContext NavigationContext)
        {
            if (!NavigationContext.QueryString.ContainsKey("historyTile")
                && !NavigationContext.QueryString.ContainsKey("historyIsNowPlayingTile"))
                return null;

            var historyTitle = string.Empty; //NavigationContext.QueryString["historyTitle"];
            var historyTag = NavigationContext.QueryString["historyTag"];
            var historySourceUrl = NavigationContext.QueryString["historySourceUrl"];
            var IsNowPlayingRestore = NavigationContext.QueryString.ContainsKey("historyIsNowPlayingTile");
            var result = new ZuneHistoryItem(historyTitle, historySourceUrl, historyTag, IsNowPlayingRestore);

            return result;
        }
    }

    public class ZuneHistoryItem
    {
        public ZuneHistoryItem(string title, string appDisplayName, string imageUri, string source, string tag)
        {
            Title = title;
            AppDisplayName = appDisplayName;
            ImageUri = imageUri;
            Source = source;
            Tag = tag;
        }

        public ZuneHistoryItem(string title, string source, string tag, bool isNowPlayingRestore)
        {
            Title = title;
            Source = source;
            IsNowPlayingRestore = isNowPlayingRestore;
            Tag = tag;
        }

        public string Title { get; set; }
        public string AppDisplayName { get; set; }
        public string ImageUri { get; set; }
        public string Source { get; set; }
        public string Tag { get; set; }
        public bool IsNowPlayingRestore { get; set; }
    }
}
